package com.hxh.learn.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.hxh.common.unification.ResultOutcome;
import com.hxh.common.utils.JwtUtil;
import com.hxh.learn.mapper.SysUserMapper;
import com.hxh.learn.model.SysUser;
import com.hxh.learn.service.ISysUserService;
import com.hxh.learn.vo.SysUserSearchVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;

import static com.hxh.common.constant.HxhConstant.BEARER;
import static com.hxh.common.constant.HxhConstant.USER_STATUS_NO;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author hxh
 * @since 2023-03-02
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserDetailsService userDetailsService;


    @Override
    public Page<SysUser> queryUserList(SysUserSearchVo vo) {
        LambdaQueryWrapper<SysUser> lambdaQuery = Wrappers.lambdaQuery(SysUser.class);
        lambdaQuery.like(StrUtil.isNotBlank(vo.getUserName()), SysUser::getUsername, vo.getUserName())
                .like(StrUtil.isNotBlank(vo.getUserNick()), SysUser::getUserNick, vo.getUserNick())
                .like(StrUtil.isNotBlank(vo.getUserPhone()), SysUser::getUserPhone, vo.getUserPhone())
                .eq(vo.getUserStatus() != null, SysUser::getUserStatus, vo.getUserStatus())
                .ge(vo.getStartTime() != null, SysUser::getCreateTime, vo.getStartTime())
                .le(vo.getEndTime() != null, SysUser::getCreateTime, vo.getEndTime());
        Page<SysUser> page = new Page<>(vo.getPageNum(), vo.getPageSize());
        return sysUserMapper.selectPage(page, lambdaQuery);
    }

    @Override
    public SysUser getByName(String userName) {
        return sysUserMapper.selectOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUsername, userName));
    }

    @Override
    public String login(String username, String password) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        SysUser sysUser=(SysUser) userDetails;
        //判断账户密码是否正确
        if (null == userDetails || !passwordEncoder.matches(password, userDetails.getPassword())) {
            throw new RuntimeException("账户或密码不正确");
        }
        if (!userDetails.isEnabled()) {
            throw new RuntimeException("账户未启用请联系管理员");
        }
        //更新Security登录信息
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //密码正确返回token
        String token = JwtUtil.getJwtToken(sysUser.getUserId(),sysUser.getUsername());
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("token", BEARER + token);
        ResultOutcome.successResult(map);
        return JSONUtil.toJsonStr(map);


    }


}
